package com.atguigu.gulimall.cart.interceptor;


import com.atguigu.common.constant.AuthServerConstant;
import com.atguigu.common.constant.CartConstant;
import com.atguigu.common.vo.MemberResponse;
import com.atguigu.gulimall.cart.vo.UserInfo;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.UUID;

/**
 * 拦截器
 *
 */

public class CartInterceptor implements HandlerInterceptor {


    /**
     * 单线程数据共享
     */
    public static ThreadLocal<UserInfo> threadLocal = new ThreadLocal<>();


    /**
     * 执行方法之前
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        UserInfo userInfo = new UserInfo();
//        HttpSession session = request.getSession();
        // 获取session中数据
        MemberResponse member = (MemberResponse) request.getSession().getAttribute(AuthServerConstant.SESSION_LOGIN_USER);
//        MemberResponse member = (MemberResponse) session.getAttribute(AuthServerConstant.SESSION_LOGIN_USER);
        if (member != null) {
            // 已登录
            userInfo.setUserId(member.getId());
        }else {
            // 未登录
        }

        if (request.getCookies() != null) {
            for (Cookie cookie : request.getCookies()) {
                if (CartConstant.TEMP_USER_COOKIE_NAME.equals(cookie.getName())){
                    userInfo.setUserKey(cookie.getValue());
                    userInfo.setTempUser(true);
                }
            }
        }

        if (StringUtils.isEmpty(userInfo.getUserKey())){
            String uuid = UUID.randomUUID().toString();
            userInfo.setUserKey(uuid);
        }

        threadLocal.set(userInfo);

        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

        UserInfo userInfo = threadLocal.get();
        // 如果没有 user-key  ， 则添加到cookie
        if (!userInfo.isTempUser()) {
            Cookie cookie = new Cookie(CartConstant.TEMP_USER_COOKIE_NAME,userInfo.getUserKey());
            cookie.setDomain("gulimall.com");
            cookie.setMaxAge(CartConstant.TEMP_USER_COOKIE_TIMEOUT);
            response.addCookie(cookie);
        }
    }
}
